package presentacion;

import dominio.Profesor;
import dao.GradoDao;
import Paneles.PanelGeneral;
import java.awt.BorderLayout;
import business.CursoBo;
import business.ProfesorBo;
import dominio.Curso;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import dominio.Grado;

/**
 *
 * @author sebastian
 */
public class InterfazAsignarDirector extends javax.swing.JFrame {

    private CursoBo cursobo;
    private ProfesorBo pbo;
    private Long indiceDocProf[];

    /** Creates new form InterfazAsignarDirector */
    public InterfazAsignarDirector() {
        initComponents();
        PanelGeneral panel = new PanelGeneral();
        this.add(panel, BorderLayout.SOUTH);
        TableColumn column = null;

        /*Cambio el ancho de las columnas de la tabla jTable1*/
        column = this.jTable1.getColumnModel().getColumn(0);
        column.setPreferredWidth(85);
        column = this.jTable1.getColumnModel().getColumn(1);
        column.setPreferredWidth(100);
        cursobo = new CursoBo();
        pbo = new ProfesorBo();
        jLabel8.setVisible(false);
        this.inicializarComboBox();
        this.inicializarTabla();
        this.poblarComboProfesNoDir();

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("empty-statement")
    private void inicializarTabla() {
        Collection<Curso> cursos = cursobo.encontrarCursosJoinProfesor(jComboBox1.getSelectedIndex());
        int numfilas = cursos.size();
        Collection<Curso> cursosPorGrado = cursobo.encontrarCursosPorGrado(jComboBox1.getSelectedIndex());
        int numeroCursosGrado = cursosPorGrado.size();
        if (cursos.size() == 0) {//si no tiene profes asignados o el grado no tiene cursos
            if (numeroCursosGrado == 0) {
                jLabel8.setVisible(true);
            }

        }
        char i[] = new char[numeroCursosGrado];

        jTable1.setModel(new DefaultTableModelImpl(
                new Object[numeroCursosGrado][2],
                new String[]{
                    "Curso", "Director"}));
        Iterator<Curso> it = cursos.iterator();
        int indicefilas = 0;
        while (it.hasNext()) {
            Curso c = it.next();
            c.getNombreCurso().getChars(c.getNombreCurso().length() - 1, c.getNombreCurso().length(), i, indicefilas);
            this.jTable1.setValueAt(c.getNombreCurso(), indicefilas, 0);
            this.jTable1.setValueAt(c.getProfesor().getNombreProfesor() + " " + c.getProfesor().getApellidoProfesor() + " \t[Doc: " + c.getProfesor().getDocProfesor() + "]", indicefilas, 1);

            indicefilas++;
        }
        if (indicefilas < numeroCursosGrado) {
            Iterator<Curso> itp = cursosPorGrado.iterator();
            char cursoactual[] = new char[numeroCursosGrado];
            boolean asignado;
            int indiceCurso = 0;
            while (itp.hasNext()) {
                asignado = false;
                Curso cg = itp.next();
//                cg.getNombreCurso().getChars(cg.getNombreCurso().length() - 1, cg.getNombreCurso().length(), cursoactual, indiceCurso);
                for (int j = 0; j < numeroCursosGrado; j++) {
                    if (cursoactual[indiceCurso] == i[j]) {
                        asignado = true;
                    }
                }
                if (!asignado) {
//                    this.jTable1.setValueAt(cg.getNombreCurso(), indicefilas, 0);
                    this.jTable1.setValueAt("No Tiene asignado", indicefilas, 1);
                    indicefilas++;
                }
                indiceCurso++;
            }
        }
    }

    private void asignacionAutomatica() {
        /**AsignacionAutomatica*/
        int sinDirector = 0;

        //primero se hace un conteo de los cursos que necesitan director
        Collection<Curso> c = cursobo.encontrarCursosSinDirector();
        sinDirector = c.size();
        Iterator<Curso> itc = c.iterator();
        int numeroCursos = c.size();
        Collection<Profesor> p = pbo.encontrarProfesores();
        int numeroProfesores = p.size();
        if (numeroCursos > numeroProfesores) {
            JOptionPane.showMessageDialog(this, "Lo sentimos!\n\nNo se puede "
                    + "realizar la operacion debido a que no existen los "
                    + "profesores suficientes para los cursos existentes\n\n"
                    + "Intente manualmente o contrate mas profesores :)",
                    "Operación Detenida", JOptionPane.ERROR_MESSAGE);
        } else {
            if (sinDirector == 0) {
                JOptionPane.showMessageDialog(this, "Le informamos que la "
                        + "operacion no es necesaria \ndebido a que todos los cursos"
                        + " existentes ya cuentan con un director",
                        "Operación Innecesaria", JOptionPane.INFORMATION_MESSAGE);
            } else {
                Collection<Profesor> pnd = pbo.encontrarProfesoresNoDirectores();
                Iterator<Profesor> itp = pnd.iterator();
                int cursosActualizados = cursobo.asignarDirectorAutomatico(itp, itc);
                if (cursosActualizados == sinDirector) {
                    JOptionPane.showMessageDialog(this, "Todos los cursos"
                            + "tienen ahora unn director",
                            "Operación Exitosa", JOptionPane.PLAIN_MESSAGE);
                }
            }
        }
    }

    private void desasignarDirector() {
        String nombreCurso = (String) jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        Long docProfesor = null;
        int confirmar = JOptionPane.showOptionDialog(this, "Esta seguro que desea "
                + "quitar el profesor ya asignado como Director ",
                "Confirmar desasignar director",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
                null, new Object[]{"Si", "No, deseo volver"}, "Si");
        if (confirmar == 0) {
            Curso c = cursobo.asignarDirectorManual(nombreCurso, docProfesor);
            poblarComboProfesNoDir();
            inicializarTabla();
        }
    }

    private void asignacionManual() {
        String nombreCurso = (String) jTable1.getValueAt(jTable1.getSelectedRow(), 0);
        Long docProfesor = indiceDocProf[jComboBox2.getSelectedIndex() - 1];
        int confirmar = 3;
        if (!jTable1.getValueAt(jTable1.getSelectedRow(), 1).equals("No Tiene asignado")) {
            confirmar = JOptionPane.showOptionDialog(this, "Esta seguro que desea "
                    + "remplazar el profesor ya asignado", ""
                    + "El curso ya tiene asignado un director",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
                    null, new Object[]{"Si", "No, deseo volver"}, "Si");
        } else {
            confirmar = 0;
        }
        if (confirmar == 0) {
            Curso c = cursobo.asignarDirectorManual(nombreCurso, docProfesor);
            poblarComboProfesNoDir();
            inicializarTabla();
        }


    }

    private void poblarComboProfesNoDir() {
        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Seleccione"}));
        Collection<Profesor> pnd = pbo.encontrarProfesoresNoDirectores();
        Iterator<Profesor> itp = pnd.iterator();
        indiceDocProf = new Long[pnd.size()];
        int i = 0;
        while (itp.hasNext()) {
            Profesor p = itp.next();
            indiceDocProf[i] = p.getDocProfesor();
            jComboBox2.addItem(p.getNombreProfesor() + " " + p.getApellidoProfesor() + " [Doc: " + p.getDocProfesor() + "]");
            i++;
        }
    }
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel5.setText("Edicion de asignación");

        jLabel6.setText("Seleccione un Profesor:");

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "  " }));

        jButton1.setText("Desasignar Director");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Lista de Cursos y Directores:");

        jButton2.setText("Realizar Asignación");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Curso", "Director"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Seleccione un grado:");

        jLabel8.setText("No tiene cursos creados");

        jLabel4.setText("Cerciorese de seleccionar la celda del curso correspondiente.");

        jCheckBox1.setText("Asignación Automática ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1020, Short.MAX_VALUE)
                    .addComponent(jLabel5)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox2, 0, 858, Short.MAX_VALUE))
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel8))
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 485, Short.MAX_VALUE)
                        .addComponent(jCheckBox1)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jCheckBox1)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        jLabel8.setVisible(false);
        inicializarTabla();
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (jCheckBox1.isSelected()) {
            asignacionAutomatica();
        } else {
            if (jTable1.getSelectedRow() != (-1)) {//si ya selecciono un curso
                if (jComboBox2.getSelectedIndex() != 0) {//si ya selecciono prof
                    asignacionManual();
                } else {
                    JOptionPane.showMessageDialog(this, "Lo sentimos!\n\nNo ha escogido un"
                            + " Profesor para asignarlo al curso escogido",
                            "Profesor Desconocido", JOptionPane.ERROR_MESSAGE);
                }

            } else {
                JOptionPane.showMessageDialog(this, "Lo sentimos!\n\nNo ha escogido un"
                        + " curso para asignarle el profesor escogido",
                        "Curso Desconocido", JOptionPane.ERROR_MESSAGE);
            }
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jTable1.getSelectedRow() != (-1)) {
            desasignarDirector();
        } else {
            JOptionPane.showMessageDialog(this, "Lo sentimos!\n\nNo ha escogido un"
                    + "curso para desasignarle el Director",
                    "Curso Desconocido", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new InterfazAsignarDirector().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void inicializarComboBox() {
        GradoDao gradoDao = new GradoDao();
        List grados = gradoDao.encontrarGrados();
        for (Iterator it = grados.iterator(); it.hasNext();) {
            Grado grado = (Grado) it.next();
            jComboBox1.addItem(String.valueOf(grado.getIdGrado()));
        }
    }

    private class DefaultTableModelImpl extends DefaultTableModel {

        public DefaultTableModelImpl(Object[][] arg0, Object[] arg1) {
            super(arg0, arg1);
        }
        boolean[] canEdit = new boolean[]{false, false};

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    }
}
